package com.bootx.service.impl;

import com.bootx.dao.RedPackageStatisticsDao;
import com.bootx.entity.RedPackageStatistics;
import com.bootx.service.RedPackageStatisticsService;
import com.bootx.util.JsonUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author black
 */
@Service
public class RedPackageStatisticsServiceImpl extends BaseServiceImpl<RedPackageStatistics,Long> implements RedPackageStatisticsService {

    @Resource
    private RedPackageStatisticsDao redPackageStatisticsDao;

    @Override
    public RedPackageStatistics findByBatchId(Long batchId) {
        return redPackageStatisticsDao.find("batchId",batchId);
    }

    @Override
    public void create(Integer count, Long batchId) {
        List<Map<String, Object>> maps1 = jdbcTemplate.queryForList("select money `amount`,openTime,orders `index` from redpackage where batchId=? order by orders asc;", batchId);
        RedPackageStatistics redPackageStatistics = findByBatchId(batchId);
        if(redPackageStatistics == null) {
            redPackageStatistics = new RedPackageStatistics();
        }
        redPackageStatistics.setBatchId(batchId);
        redPackageStatistics.setCount(count);
        redPackageStatistics.setOpenInfo(JsonUtils.toJson(maps1));
        /**
         * 后面20个包的数据拉过来
         */
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select money `amount`,openTime from redpackage where batchId=? order by orders desc limit 20;", batchId);
        for (int i = 1; i <= maps.size(); i++) {
            maps.get(i-1).put("position",i);
        }
        if(redPackageStatistics.isNew()){
            super.save(redPackageStatistics);
        }else{
            super.update(redPackageStatistics);
        }
    }
}
